﻿ko.bindingHandlers.autoComplete = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var settings = valueAccessor();

        var selectedOption = settings.selected;
        var options = settings.options;

        var updateElementValueWithLabel = function (event, ui) {
            event.preventDefault();

            $(element).val(ui.item.label);
            $(element).closest("div").children("input[type=hidden]").val(ui.item.value);

            if (typeof ui.item !== "undefined") {
                selectedOption(ui.item);
            }
        };

        $(element).autocomplete({
            source: options,
            select: function (event, ui) {
                updateElementValueWithLabel(event, ui);
            },
            focus: function (event, ui) {
                updateElementValueWithLabel(event, ui);
            },
            change: function (event, ui) {
                updateElementValueWithLabel(event, ui);
            }
        });
    }
};

function ViewModel(remoteData) {
    this.model = remoteData;

    this.selectedOption = ko.observable();
    this.options = this.model.map(function (element) {
        return {
            label: element.Value,
            value: element.ID,
            object: element
        };
    });
}